# AI 智能客服业务助理 PowerShell 启动脚本
# Windows PowerShell 7.5 兼容版本

param(
    [switch]$SkipModelPull,
    [switch]$SkipFrontend,
    [switch]$Verbose
)

# 设置错误处理
$ErrorActionPreference = "Stop"
$VerbosePreference = if ($Verbose) { "Continue" } else { "SilentlyContinue" }

# 颜色输出函数
function Write-ColorOutput {
    param(
        [string]$Message,
        [string]$Color = "White"
    )
    Write-Host $Message -ForegroundColor $Color
}

function Write-Success {
    param([string]$Message)
    Write-ColorOutput "✅ $Message" "Green"
}

function Write-Error {
    param([string]$Message)
    Write-ColorOutput "❌ $Message" "Red"
}

function Write-Warning {
    param([string]$Message)
    Write-ColorOutput "⚠️  $Message" "Yellow"
}

function Write-Info {
    param([string]$Message)
    Write-ColorOutput "ℹ️  $Message" "Cyan"
}

# 获取脚本所在目录
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location $ScriptDir

Write-ColorOutput "🚀 启动 AI 智能客服业务助理..." "Magenta"
Write-ColorOutput "📍 工作目录: $ScriptDir" "Gray"

# 检查环境配置文件
$envFile = Join-Path $ScriptDir ".env"
$envExampleFile = Join-Path $ScriptDir "env-example.txt"

if (-not (Test-Path $envFile)) {
    Write-Warning "未找到 .env 文件，正在从模板创建..."
    if (Test-Path $envExampleFile) {
        Copy-Item $envExampleFile $envFile
        Write-Success "已创建 .env 文件"
        Write-Info "请编辑 .env 文件配置必要的环境变量"
        Write-Info "按任意键继续..."
        $null = Read-Host
    } else {
        Write-Error "未找到环境配置模板文件"
        exit 1
    }
}

# 加载环境变量
Write-Info "加载环境配置..."
if (Test-Path $envFile) {
    Get-Content $envFile | Where-Object { $_ -match '^[^#].*=' } | ForEach-Object {
        $key, $value = $_.Split('=', 2)
        $key = $key.Trim()
        $value = $value.Trim()
        [Environment]::SetEnvironmentVariable($key, $value)
        Write-Verbose "设置环境变量: $key = $value"
    }
    Write-Success "环境配置加载完成"
}

# 检查并启动 Ollama 服务
function Test-OllamaService {
    param([string]$BaseUrl = "http://localhost:11434")

    try {
        $response = Invoke-WebRequest -Uri "$BaseUrl/api/tags" -TimeoutSec 5 -ErrorAction SilentlyContinue
        return $response.StatusCode -eq 200
    } catch {
        return $false
    }
}

function Start-OllamaService {
    Write-Info "检查 Ollama 服务状态..."

    $ollamaBaseUrl = $env:OLLAMA_BASE_URL
    if (-not $ollamaBaseUrl) {
        $ollamaBaseUrl = "http://localhost:11434"
    }

    # 检查 Ollama 是否安装
    $ollamaPath = Get-Command ollama -ErrorAction SilentlyContinue
    if (-not $ollamaPath) {
        Write-Warning "未检测到 Ollama 安装"
        Write-Info "请从 https://ollama.com/download 安装 Ollama"
        Write-Info "安装完成后重新运行此脚本"
        exit 1
    }

    # 检查 Ollama 服务是否运行
    if (-not (Test-OllamaService $ollamaBaseUrl)) {
        Write-Warning "Ollama 服务未运行，尝试启动..."
        try {
            Start-Process -FilePath "ollama" -ArgumentList "serve" -NoNewWindow
            Write-Info "等待 Ollama 服务启动..."
            Start-Sleep -Seconds 5
        } catch {
            Write-Error "无法启动 Ollama 服务: $_"
            exit 1
        }
    }

    # 再次检查服务状态
    if (Test-OllamaService $ollamaBaseUrl) {
        Write-Success "Ollama 服务运行正常"
    } else {
        Write-Error "Ollama 服务启动失败"
        Write-Info "请手动运行: ollama serve"
        exit 1
    }

    return $ollamaBaseUrl
}

# 拉取 Ollama 模型
function Pull-OllamaModel {
    param([string]$ModelName = "qwen2.5:7b")

    if ($SkipModelPull) {
        Write-Info "跳过模型拉取"
        return
    }

    Write-Info "检查模型 $ModelName 是否已安装..."

    try {
        $installedModels = & ollama list 2>$null
        if ($installedModels -match $ModelName) {
            Write-Success "模型 $ModelName 已存在"
            return
        }
    } catch {
        Write-Warning "无法检查已安装的模型"
    }

    Write-Info "正在拉取模型 $ModelName..."
    try {
        & ollama pull $ModelName
        Write-Success "模型 $ModelName 拉取完成"
    } catch {
        Write-Error "模型拉取失败: $_"
        Write-Info "请手动运行: ollama pull $ModelName"
        exit 1
    }
}

# 检查 Python 环境
function Test-PythonEnvironment {
    param([string]$RequirementsFile)

    Write-Info "检查 Python 环境..."

    # 检查 Python
    $pythonCmd = Get-Command python -ErrorAction SilentlyContinue
    if (-not $pythonCmd) {
        $pythonCmd = Get-Command python3 -ErrorAction SilentlyContinue
    }

    if (-not $pythonCmd) {
        Write-Error "未找到 Python，请安装 Python 3.8+"
        exit 1
    }

    Write-Success "Python 环境正常"

    # 检查并安装依赖
    if (Test-Path $RequirementsFile) {
        Write-Info "检查并安装 Python 依赖..."
        try {
            & $pythonCmd.Source -m pip install --upgrade pip
            & $pythonCmd.Source -m pip install -r $RequirementsFile
            Write-Success "Python 依赖安装完成"
        } catch {
            Write-Error "Python 依赖安装失败: $_"
            exit 1
        }
    }

    return $pythonCmd.Source
}

# 启动后端服务
function Start-BackendService {
    param([string]$PythonCmd)

    $backendDir = Join-Path $ScriptDir "backend"
    $mainFile = Join-Path $backendDir "main.py"

    if (-not (Test-Path $mainFile)) {
        Write-Error "后端文件不存在: $mainFile"
        return $false
    }

    Write-Info "启动后端服务..."

    try {
        $backendProcess = Start-Process -FilePath $PythonCmd -ArgumentList "-m", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--reload" -NoNewWindow -PassThru
        Write-Success "后端服务启动中 (PID: $($backendProcess.Id))"
        return $backendProcess
    } catch {
        Write-Error "后端服务启动失败: $_"
        return $false
    }
}

# 启动前端服务
function Start-FrontendService {
    $frontendDir = Join-Path $ScriptDir "frontend"

    if (-not (Test-Path $frontendDir)) {
        Write-Warning "前端目录不存在，跳过前端启动"
        return $false
    }

    # 检查 Node.js
    $nodeCmd = Get-Command node -ErrorAction SilentlyContinue
    if (-not $nodeCmd) {
        Write-Warning "未找到 Node.js，请安装 Node.js 16+"
        Write-Info "前端服务跳过，请手动启动"
        return $false
    }

    # 检查 package.json
    $packageJson = Join-Path $frontendDir "package.json"
    if (-not (Test-Path $packageJson)) {
        Write-Warning "前端项目文件不完整，跳过启动"
        return $false
    }

    Write-Info "启动前端服务..."

    try {
        Push-Location $frontendDir

        # 安装依赖（如果需要）
        if (-not (Test-Path "node_modules")) {
            Write-Info "安装前端依赖..."
            & npm install
        }

        # 启动开发服务器
        $frontendProcess = Start-Process -FilePath "npm" -ArgumentList "run", "dev" -NoNewWindow -PassThru
        Pop-Location

        Write-Success "前端服务启动中 (PID: $($frontendProcess.Id))"
        return $frontendProcess
    } catch {
        Write-Error "前端服务启动失败: $_"
        Pop-Location
        return $false
    }
}

# 启动 Mock 服务
function Start-MockService {
    param([string]$PythonCmd)

    $mockDir = Join-Path $ScriptDir "order-mock"
    $appFile = Join-Path $mockDir "app.py"

    if (-not (Test-Path $appFile)) {
        Write-Warning "Mock 服务文件不存在，跳过启动"
        return $false
    }

    Write-Info "启动 Mock 服务..."

    try {
        Push-Location $mockDir
        $mockProcess = Start-Process -FilePath $PythonCmd -ArgumentList $appFile -NoNewWindow -PassThru
        Pop-Location

        Write-Success "Mock 服务启动中 (PID: $($mockProcess.Id))"
        return $mockProcess
    } catch {
        Write-Error "Mock 服务启动失败: $_"
        Pop-Location
        return $false
    }
}

# 等待服务启动
function Wait-ServicesReady {
    Write-Info "等待服务启动..."

    # 等待后端服务
    $maxRetries = 30
    $retryCount = 0

    while ($retryCount -lt $maxRetries) {
        try {
            $response = Invoke-WebRequest -Uri "http://localhost:8000/health" -TimeoutSec 5 -ErrorAction SilentlyContinue
            if ($response.StatusCode -eq 200) {
                Write-Success "后端服务启动成功: http://localhost:8000"
                break
            }
        } catch {
            # 服务还未就绪
        }

        $retryCount++
        Write-Verbose "等待后端服务启动... ($retryCount/$maxRetries)"
        Start-Sleep -Seconds 2
    }

    if ($retryCount -eq $maxRetries) {
        Write-Warning "后端服务启动超时，请检查日志"
    }

    # 检查其他服务
    try {
        $response = Invoke-WebRequest -Uri "http://localhost:5000/health" -TimeoutSec 5 -ErrorAction SilentlyContinue
        if ($response.StatusCode -eq 200) {
            Write-Success "Mock 服务启动成功: http://localhost:5000"
        }
    } catch {
        Write-Warning "Mock 服务未就绪"
    }

    try {
        $response = Invoke-WebRequest -Uri "http://localhost:3000" -TimeoutSec 5 -ErrorAction SilentlyContinue
        if ($response.StatusCode -eq 200) {
            Write-Success "前端服务启动成功: http://localhost:3000"
        }
    } catch {
        Write-Warning "前端服务未就绪"
    }
}

# 主函数
function Start-Main {
    try {
        # 启动 Ollama 服务
        $ollamaUrl = Start-OllamaService

        # 拉取模型
        $modelName = $env:OLLAMA_MODEL_NAME
        if (-not $modelName) {
            $modelName = "qwen2.5:7b"
        }
        Pull-OllamaModel $modelName

        # 检查 Python 环境
        $pythonCmd = Test-PythonEnvironment (Join-Path $ScriptDir "backend\requirements.txt")

        # 启动各个服务
        $backendProcess = Start-BackendService $pythonCmd

        if (-not $SkipFrontend) {
            $frontendProcess = Start-FrontendService
        }

        $mockProcess = Start-MockService $pythonCmd

        # 等待服务就绪
        Wait-ServicesReady

        # 显示服务信息
        Write-ColorOutput "" "Magenta"
        Write-ColorOutput "🎉 AI 智能客服业务助理启动完成！" "Green"
        Write-ColorOutput "" "Magenta"
        Write-ColorOutput "📱 前端界面: http://localhost:3000" "Cyan"
        Write-ColorOutput "🔧 后端 API: http://localhost:8000" "Cyan"
        Write-ColorOutput "📊 API 文档: http://localhost:8000/docs" "Cyan"
        Write-ColorOutput "🧪 Mock 服务: http://localhost:5000" "Cyan"
        Write-ColorOutput "" "Magenta"
        Write-ColorOutput "💡 使用提示:" "Yellow"
        Write-ColorOutput "   - 停止服务: Ctrl+C 或关闭 PowerShell 窗口" "Yellow"
        Write-ColorOutput "   - 查看日志: 在各个服务窗口中查看" "Yellow"
        Write-ColorOutput "" "Magenta"

        # 保持脚本运行，显示状态
        Write-Info "服务正在运行中... 按 Ctrl+C 停止"

        # 等待用户中断
        try {
            while ($true) {
                Start-Sleep -Seconds 10

                # 检查服务状态
                try {
                    $response = Invoke-WebRequest -Uri "http://localhost:8000/health" -TimeoutSec 5 -ErrorAction SilentlyContinue
                    if ($response.StatusCode -ne 200) {
                        Write-Warning "后端服务可能已停止"
                    }
                } catch {
                    Write-Warning "无法连接到后端服务"
                }
            }
        } catch {
            Write-Info "正在停止服务..."
        }

        # 清理进程
        if ($backendProcess) {
            Stop-Process -Id $backendProcess.Id -ErrorAction SilentlyContinue
        }
        if ($frontendProcess) {
            Stop-Process -Id $frontendProcess.Id -ErrorAction SilentlyContinue
        }
        if ($mockProcess) {
            Stop-Process -Id $mockProcess.Id -ErrorAction SilentlyContinue
        }

        Write-Success "服务已停止"

    } catch {
        Write-Error "启动过程中出现错误: $_"
        Write-Info "请检查上述错误信息并重试"
        exit 1
    }
}

# 执行主函数
Start-Main
